/*
 *   from config.js
 * */

function genNewsTime(milliTime) {
	var newTime = new Date(milliTime);
	var offset = newTime.getHours() - newTime.getUTCHours();
	if (offset > 0) offset = "+" + offset;
	return newTime.toLocaleString().replace(/:00$/,"") + " GMT" + offset + ":00";
}
function genNewsTime2(milliTime) {
	var newTime = new Date(milliTime);
	return newTime.toLocaleString().replace(/:00$/,"");
}

// 解析url
function getQuery(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  decodeURIComponent(r[2]); return false;
}

/*
 *   from news.js
 * */

var stockData = [];     // 存相关股票数组

// 跳转原生APP
function skipStock(context) {

	var context = JSON.stringify(stockData[context]);

	var isAndroid = /(Android)/i.test(navigator.userAgent); //android终端
	var isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); //ios终端
	if(isAndroid){
		if(window.WebullApp){
			window.WebullApp.openRelatedStock(context);
		}else{
			var obj = JSON.parse(context);
			window.webViewBridge.callHandler(
				"related_ticker",
				obj,
				function (responseData) {
					var str = JSON.stringify(responseData);
				}
			);
		}
	}else if(isiOS){
		window.webkit.messageHandlers.Action.postMessage(context);
	}
}

// 打开新链接
function openNewWeb( _url ) {

	var data = {
		url : _url
	};
	var _int = getQuery('android_sdk_int');

	if (_int){
		if(_int >= 17){
			if(window.WebullApp && window.WebullApp.openWeb){
				window.WebullApp.openWeb(JSON.stringify(data));
			}
		}else{
			var alertData = {
				methodName: "openWeb",
				methodParameter: data
			};

			alert(JSON.stringify(alertData));
		}
	} else {
		location.href = _url;
	}
}

// 打开新链接
function resizeHeight( _height ) {

	var data = {
		height : _height
	};
	var _int = getQuery('android_sdk_int');

	if(_int){
		if (_int >= 17){
			if(window.WebullApp && window.WebullApp.resizeHeight){
				window.WebullApp.resizeHeight(JSON.stringify(data));
			}
		} else {
			var alertData = {
				methodName: "resizeHeight",
				methodParameter: data
			};

			alert(JSON.stringify(alertData));
		}
	}
}

function shareNews(){
	var obj = {};obj.title = $('#id_title').html()  || '';obj.url = window.location.href  || '';obj.general = $('#id_general').html() || '';
	var isAndroid = /(Android)/i.test(navigator.userAgent); //android终端
	var isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); //ios终端
	var context = JSON.stringify(obj);
	if(isAndroid){
		window.WebullApp.setShareData(context);
	}else{
		window.webkit.messageHandlers.NewsShare.postMessage(context);
	}
}

// 展开收起股票列表
function toggleStocks(){

	var stockArea = document.querySelector('.stock-relative');
	var trigIco = document.querySelector('.arrow-ico');
	var stockHeight = stockData.length * 43 - 1;

	if(!trigIco.classList.contains('top')){
		stockArea.style.height = stockHeight + 'px';
	}else{
		stockArea.style.height = '85px';
	}

	trigIco.classList.toggle('top');
}

function closeDownload() {
	document.querySelector('#download-tip').style.display = 'none';
}


function closeStocks() {
	document.querySelector('#download-stock').style.display = 'none';
}

window.onload = function () {

	if(navigator.userAgent.indexOf('webull') < 0 && navigator.userAgent.indexOf('stocks') < 0){
		if(getQuery('sp') == 1){//显示stocks的ad
			document.querySelector('#download-stock').style.display = 'block';
		}else{
			document.querySelector('#download-tip').style.display = 'block';
		}
	}else{
		document.body.style.paddingBottom = 0;
	}

	var isStocksOpen = (navigator.userAgent.indexOf('stocks') > 0 || getQuery('sp')==1);

	var vtheme = 0;
	var _theme = getQuery('theme');

	if(!_theme ){
		_theme = getQuery('style') || 0;
	}


	document.querySelector('body').classList.remove('style-2');

	if ( _theme == 0 ){
		vtheme = 0;
		document.querySelector('body').classList.add('style-1');
	}else if( _theme == 1 ){
		vtheme = 1;
		document.querySelector('body').classList.add('style-2');
	}else if( _theme == 2 ){
		vtheme = 2;
		document.querySelector('body').classList.add('style-3');
	}

	var _body = document.getElementsByTagName('body');
	_body[0].style.display = 'block';

	if (getQuery('color') == 3) {
		document.querySelector('body').classList.add('color-3');
	} else if (getQuery('color') == 2) {
		document.querySelector('body').classList.add('color-2');
	} else {
		document.querySelector('body').classList.add('color-1');
	}

	var v_attach = getQuery('attach');
	var vlang = getQuery('hl');

	if (vlang == undefined){
		vlang = "en";
	}

	//拉取相关股票
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
		if(xhr.readyState === 4){
			if((xhr.status >= 200 && xhr.status < 300) || (xhr.status === 304)){

				stockData = JSON.parse(xhr.responseText);
				if (stockData.length > 0 ) {
					for(var i = 0; stockData.length >= 10 ? i < 10 : i < stockData.length ; i ++ ){

						var tit = stockData[i].nfirst == 1 ? stockData[i].stockName : stockData[i].stockSymbol;
						var txt = stockData[i].nfirst == 1 ? stockData[i].stockSymbol : stockData[i].stockName;
						var color = '';
						var prise = stockData[i].price || '-';
						var rate = stockData[i].changeRate ? (stockData[i].changeRate*100).toFixed(2) : '-';

						if(stockData[i].changeRate){
							if(stockData[i].changeRate != 0){
								color = stockData[i].changeRate > 0 ? 'red' : 'green';
							}
						}

						console.log(color);

						var inner = '<div class="stock" index="'+ i +'" onclick="skipStock('+ i +')">'+
							'<div class="name">'+
							'<p class="stock-tit">'+ tit +'</p>'+
							'<p class="stock-txt">'+ txt +'</p>'+
							'</div>'+
							'<span class="price '+ color +'">&nbsp;'+ prise +'</span>'+
							'<span class="rate '+ color +'">&nbsp;'+ rate +'%</span>'+
							'</div>';

						var elem = document.createElement('div');
						elem.innerHTML = inner;
						if(document.getElementById('id_rela_stock')){
							document.getElementById('id_rela_stock').style.display = 'block';
						}
						document.querySelector('.stock-area').appendChild(elem.childNodes[0]);
					}

					if( stockData.length > 2 ){
						var trig = document.querySelector('.trig');
						trig.style.display = 'block';
						document.querySelector('.stock-area').style.height = '85px';
					}

					document.querySelector('.stock-relative').style.display = 'block';
				}
			}else{
				console.log("Response wa 1  unsuccessful: " + xhr.status);
			}
		}
	};

	var relateNews = document.getElementById('relate-news');
	var xhr2 = new XMLHttpRequest();
	var parseDate = function(str) {
		var date = Date.parse(str);
		if (!date) {
			var reg = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)/
			var regRes = reg.exec(str)
			date = new Date(Date.UTC(parseInt(regRes[1]), parseInt(regRes[2])-1,
				parseInt(regRes[3]), parseInt(regRes[4]), parseInt(regRes[5]),
				parseInt(regRes[6])));
		}
		return date;
	};


	xhr2.onreadystatechange = function () {
		if(xhr2.readyState === 4){
			if((xhr2.status >= 200 && xhr2.status < 300) || (xhr2.status === 304)){

				var content = JSON.parse(xhr2.responseText);
				var news = content.news;

				if ( 'succ' == content.code && news.length > 0 ) {
					var elemHd = document.createElement('div');
					elemHd.innerHTML = content.label;
					document.querySelector('#relate-news-hd').appendChild(elemHd.childNodes[0]);

					for (var i = news.length - 1; i >= 0; i--) {

						var datetime = genNewsTime2(parseDate(news[i].newsTime));

						var itemClass = 'item no-img';
						if (news[i].mainPic && news[i].mainPic != '') {
							itemClass = 'item';
						};

						var _sp1=	isStocksOpen?'&sp=1':'';
						var _url = news[i].newsUrl + '?theme=' + vtheme + '&hl=' + vlang + _sp1;

						var inner = '<a href="javascript:;" onclick="openNewWeb(\'' + _url + '\')" class="'+ itemClass +'">'+
							'<div class="title">'+ news[i].title +'</div>'+
							'<div class="date">'+ news[i].sourceName +' · '+ datetime +'</div>'+
							'<img src="'+ news[i].mainPic +'">'+
							'</a>';

						var elem = document.createElement('div');
						elem.innerHTML = inner;
						document.querySelector('#relate-news-bd').appendChild(elem.childNodes[0]);
					};

				}else{
					relateNews.style.display = 'none';
				}

				var _height = document.body.scrollHeight;
				resizeHeight(_height);

			}else{
				console.log("Response wa 2 unsuccessful: " + xhr2.status);
			}
		}
	};

//	if(isStocksOpen ==false){
//		setTimeout(function(){
//			xhr.open('GET',app_cneter_news_md5_url + url_md5 + "?hl="+vlang+"&attach="+v_attach, true);
//			xhr.send(null);
//		},100);
//	}
	if(relateNews){
		setTimeout(function(){
			xhr2.open('GET',app_cneter_rela_news_md5_url + url_md5 + "?hl="+vlang, true);
			xhr2.send(null);
		},100);
	}
};

/*
 *   from meow-bridge.js
 * */

(function (funcName, baseObj) {
	"use strict";
	// The public function name defaults to window.docReady
	// but you can modify the last line of this function to pass in a different object or method name
	// if you want to put them in a different namespace and those will be used instead of
	// window.docReady(...)
	funcName = funcName || "ready";
	baseObj = baseObj || window;
	var readyList = [];
	var readyFired = false;
	var readyEventHandlersInstalled = false;

	// call this when the document is ready
	// this function protects itself against being called more than once
	function ready() {
		if (!readyFired) {
			// this must be set to true before we start calling callbacks
			readyFired = true;
			for (var i = 0; i < readyList.length; i++) {
				// if a callback here happens to add new ready handlers,
				// the docReady() function will see that it already fired
				// and will schedule the callback to run right after
				// this event loop finishes so all handlers will still execute
				// in order and no new ones will be added to the readyList
				// while we are processing the list
				readyList[i].fn.call(window, readyList[i].ctx);
			}
			// allow any closures held by these functions to free
			readyList = [];
		}
	}

	function readyStateChange() {
		if (document.readyState === "complete") {
			ready();
		}
	}

	// This is the one public interface
	// docReady(fn, context);
	// the context argument is optional - if present, it will be passed
	// as an argument to the callback
	baseObj[funcName] = function (callback, context) {
		// if ready has already fired, then just schedule the callback
		// to fire asynchronously, but right away
		if (readyFired) {
			setTimeout(function () {
				callback(context);
			}, 1);
			return;
		} else {
			// add the function and context to the list
			readyList.push({fn: callback, ctx: context});
		}
		// if document already ready to go, schedule the ready function to run
		// IE only safe when readyState is "complete", others safe when readyState is "interactive"
		if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
			setTimeout(ready, 1);
		} else if (!readyEventHandlersInstalled) {
			// otherwise if we don't have event handlers installed, install them
			if (document.addEventListener) {
				// first choice is DOMContentLoaded event
				document.addEventListener("DOMContentLoaded", ready, false);
				// backup is window load event
				window.addEventListener("load", ready, false);
			} else {
				// must be IE
				document.attachEvent("onreadystatechange", readyStateChange);
				window.attachEvent("onload", ready);
			}
			readyEventHandlersInstalled = true;
		}
	}
})("ready", window);

window.Client = function () {
	var ua = navigator.userAgent;

	var system = {iOS: false, android: false};

	system.iOS = ua.indexOf("iPhone") > -1 || ua.indexOf("iPad") > -1;

	//determine iOS version
	if (navigator.platform.indexOf("Mac") == 0 && ua.indexOf("Mobile") > -1) {
		if (/CPU (?:iPhone )?OS (\d+_\d+)/.test(ua)) {
			system.iOS = parseFloat(RegExp.$1.replace("_", "."));
		} else {
			system.iOS = 2; //can’t really detect - so guess
		}
	}

	if (/Android (\d+\.\d+)/.test(ua)) {
		system.android = parseFloat(RegExp.$1);
	}

	return system;
}();

(function (root) {

	function MeowWebViewJavascriptBridge() {
		this.iOS = window.Client.iOS;
		this.android = window.Client.android;
	}

	MeowWebViewJavascriptBridge.prototype.setupWebViewJavascriptBridge = function (callback) {
		if (window.WebViewJavascriptBridge) {
			return callback(WebViewJavascriptBridge);
		}
		if (window.WVJBCallbacks) {
			return window.WVJBCallbacks.push(callback);
		}

		window.WVJBCallbacks = [callback];
		var WVJBIframe = document.createElement('iframe');
		WVJBIframe.style.display = 'none';
		WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
		document.documentElement.appendChild(WVJBIframe);
		setTimeout(function () {
			document.documentElement.removeChild(WVJBIframe)
		}, 0)
	};

	MeowWebViewJavascriptBridge.prototype.callHandler = function (handlerName, data, callback) {
		this.setupWebViewJavascriptBridge(function (bridge) {
			bridge.callHandler(handlerName, data, callback);
		});
	};

	MeowWebViewJavascriptBridge.prototype.registerHandler = function (handlerName, callback) {
		this.setupWebViewJavascriptBridge(function (bridge) {
			bridge.registerHandler(handlerName, callback);
		});
	};

	root.webViewBridge = new MeowWebViewJavascriptBridge();
})(window);

/*
 *   from google
 * */

setTimeout(function(){
	(function(i,s,o,g,r,a,m){
		i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
				(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
			m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

	if(location.href.indexOf('webull') ){
		ga('create', 'UA-91649277-1', 'auto');
		ga('send', 'pageview');
	}else{
		ga('create', 'UA-91649277-2', 'auto');
		ga('send', 'pageview');
	}


	(function(i,s,o,g,r,a,m){
		i['wlasH']=r;
		i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},
			a=s.createElement(o),
			m=s.getElementsByTagName(o)[0];a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','https://wlas.webull.com/wlas.events.js','wla');

	var  nid_= getQuery('nid')||0;
	var  tid_= getQuery('tid')||0;
	if(nid_  || tid_ ){
		wla('news',tid_, nid_, 0);
		wla('news',tid_, nid_, 4);
		wla('news',tid_, nid_, 10);
		wla('news',tid_, nid_, 30);
		wla('news',tid_, nid_, 60);
	}

},200);
